package top.honlnk.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;


@Slf4j
public class StringToArrayUtil {
    public String[][] stringTo2DArray(String str) {
        // 将字符串转换为JSONArray
        JSONArray jsonArray;
        try {
            jsonArray = new JSONArray(str);

            // 动态确定数组大小
            int rows = jsonArray.length();
            int cols = rows > 0 ? jsonArray.getJSONArray(0).length() : 0;
            String[][] array2D = new String[rows][cols];

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray innerArray = jsonArray.getJSONArray(i);
                for (int j = 0; j < innerArray.length(); j++) {
                    if (innerArray.isNull(j)) {
                        array2D[i][j] = ""; // 或者根据业务需求设置一个默认值
                    } else {
                        array2D[i][j] = innerArray.getString(j);
                    }
                }
            }
            return array2D;
        } catch (JSONException e) {
            log.error("将JSON字符串解析为2D数组时出错：", e);
            throw new RuntimeException(e);
        }
    }

    public String[][][] stringTo3DArray(String str) {
        // 将字符串转换为JSONArray
        JSONArray jsonArray;
        try {
            jsonArray = new JSONArray(str);
            // 创建三维数组
            int depth = jsonArray.length();
            String[][][] array3D = new String[depth][][];

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray innerArray2D = jsonArray.getJSONArray(i);
                int rows = innerArray2D.length();
                array3D[i] = new String[rows][];

                for (int j = 0; j < innerArray2D.length(); j++) {
                    JSONArray innerArray1D = innerArray2D.getJSONArray(j);
                    int cols = innerArray1D.length();
                    array3D[i][j] = new String[cols];

                    for (int k = 0; k < innerArray1D.length(); k++) {
                        if (innerArray1D.isNull(k)) {
                            array3D[i][j][k] = ""; // 或者根据业务需求设置一个默认值
                        } else {
                            array3D[i][j][k] = innerArray1D.getString(k);
                        }
                    }
                }
            }
            return array3D;
        } catch (JSONException e) {
            log.error("将JSON字符串解析为3D数组时出错：", e);
            throw new RuntimeException(e);
        }
    }
}
